import os
from scipy.io import wavfile
from scipy import signal

input_directory = "/home/work_nfs2/xshi/corpus/aishell1"
output_directory = "/home/work_nfs2/xshi/corpus/aishell1_8k"
target_sample_rate = 8000

def downsample_wav(input_path, output_path):
    sample_rate, data = wavfile.read(input_path)
    
    if sample_rate != target_sample_rate:
        resampled_data = signal.resample(data, int(len(data) * target_sample_rate / sample_rate))
        wavfile.write(output_path, target_sample_rate, resampled_data.astype(data.dtype))
    else:
        os.copy(input_path, output_path)

if not os.path.exists(output_directory):
    os.makedirs(output_directory)

for root, _, files in os.walk(input_directory):
    for filename in files:
        if filename.endswith(".wav"):
            input_path = os.path.join(root, filename)
            relative_path = os.path.relpath(input_path, input_directory)
            output_path = os.path.join(output_directory, relative_path)
            
            if not os.path.exists(os.path.dirname(output_path)):
                os.makedirs(os.path.dirname(output_path))
            
            downsample_wav(input_path, output_path)
